package com.example.trb.service.department;

import com.example.trb.component.EncodeComponent;
import com.example.trb.dto.ObjectDTO;
import com.example.trb.entity.Department;
import com.example.trb.entity.ReviewForm;
import com.example.trb.entity.ReviewMeeting;
import com.example.trb.mapper.DepartmentMapper;
import com.example.trb.mapper.ReviewMeetingMapper;
import com.example.trb.service.review.ReviewFormService;
import com.example.trb.util.StringUtils;
import com.example.trb.util.result.SysReturnCode;
import com.example.trb.util.result.UserReturnCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DepartmentService {
    @Autowired
    DepartmentMapper departmentMapper;
    @Autowired
    EncodeComponent encoder;
    @Autowired
    ReviewFormService rfService;
    @Autowired
    ReviewMeetingMapper rmMapper;

    public ObjectDTO listForm(Integer departmentId, String status, String reviewYear, String level) {
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("department_id", departmentId);
        List<ReviewMeeting> result = rmMapper.selectByMap(queryMap);
        if (result.isEmpty())
            return new ObjectDTO(null, UserReturnCode.USER_NOT_EXIST);

        queryMap = new HashMap<>();
        if (!StringUtils.isBlank(status))
            queryMap.put("status", status);
        if (!StringUtils.isBlank(reviewYear))
            queryMap.put("review_year", reviewYear);
        if (!StringUtils.isBlank(level))
            queryMap.put("level", level);
        queryMap.put("review_meeting_id", result.get(0).getId());
        List<ReviewForm> data = rfService.listReviewForm(queryMap);
        return new ObjectDTO(data, SysReturnCode.OK);
    }

    public ObjectDTO login(Department data) {
        ObjectDTO dto = new ObjectDTO();
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("account", data.getAccount());
        List<Department> results = departmentMapper.selectByMap(queryMap);

        if (results.isEmpty()) {
            dto.setCode(UserReturnCode.USER_NOT_EXIST);
            return dto;
        }

        Department result = results.get(0);
        if (data.getPassword().equals(result.getPassword())) {
            result.setPassword(null);
            dto.setCode(UserReturnCode.OK);
            dto.setData(result);
            return dto;
        }

        dto.setCode(UserReturnCode.PASSWORD_OR_ACCOUNT_ERROR);
        return dto;
    }
}
